import React, { Component } from 'react'
import { AutoComplete, Button, Card, Divider, Icon, message, Table, Tag } from 'antd'
import { connect } from 'react-redux'
import '../../../../less/index.less'
import { Link, withRouter } from 'react-router-dom'
import * as taskActions from '../../../../actions/task'
import * as myStudentsActions from '../../../../actions/myStudents'
import { batchFollow, batchUnFollow } from '../../../../actions/myStudents'
import NOTIFICATION_TYPE from '../../../../constant/notification-type'
import * as notification from '../../../../actions/notification'
import { FormattedMessage } from 'react-intl'
import { getUploadUrl } from '../../../../constant/upload-url'
import { TwsReactMarkdownEditor, TwsReactMarkdownPreview } from 'tws-antd'
import { editStudentTags, getStudentTagsByProgramId } from '../../../../actions/student-tag'
import EditTagModal from './edit-tag-modal'
import CommentModal from './comment-modal'
import SearchToolPane from './search-tool-pane'
import { getStudentsByProgramId } from '../../../../actions/program'

const Option = AutoComplete.Option

class MyStudentBox extends Component {
  state = {
    dataSource: [],
    expandIconAsCell: false,
    expandRowByClick: true,
    expandedRowKeys: [],
    commentsContent: '',
    commentModalVisible: false,
    userName: '',
    content: '',
    currentSelectedTagIds: [],
    currentSelectedStudentId: 0,
    tagModalVisible: false,
  }

  componentDidMount () {
    const {programId} = this.props
    this.props.getStudentTagsByProgramId(programId)
    this.props.getStudentsByPrograms(programId)
  }

  gotoSection (studentId) {
    return '/program/' + this.props.programId + '/student/' + studentId
  }

  follow (followerId) {
    const {programId} = this.props
    this.props.follow(followerId, programId, () => {
      this.props.notification(followerId, programId, NOTIFICATION_TYPE.TUTOR_FOLLOW_STUDENT)
    })
  }
  batchFollow(programId, tutorId, studentIds){
    this.props.batchFollow(programId,tutorId,studentIds,(studentIds, programId) =>
      studentIds.split(',').forEach(followerId =>
        this.props.notification(followerId, programId, NOTIFICATION_TYPE.TUTOR_FOLLOW_STUDENT)
      )
    )
  }

  unFollow (followerId) {
    this.props.unFollow(followerId, this.props.programId)
  }

  search (value) {
    if (value.trim() !== '') {
      this.props.getUserByNameOrEmail(value, this.props.programId, (data) => {
        this.setState({dataSource: data || []})
      })
    }
  }

  getCompleteName (user) {
    const name = user.name || ''
    const userName = user.username || ''

    return `${name}(@${userName})`
  }

  onExpandedRowsChange (index, record) {
    this.setState({
      expandedRowKeys: [index],
      concealComment: record.concealComment ? record.concealComment.content : ''
    })
  }

  handleCancel () {
    this.setState({
      expandedRowKeys: []
    })
  }

  handleCommentChange (commentsContent) {
    this.setState({commentsContent})
  }

  handleConcealComment (record) {
    const {commentsContent} = this.state
    this.props.addConcealComment(record.student.id, this.props.programId, commentsContent)
    this.setState({
      expandedRowKeys: [],
      commentsContent: '',
    })
  }

  expandedRowRender (settings, record) {
    return <div>
      <TwsReactMarkdownEditor
        action={getUploadUrl(settings.appContextPath)}
        value={record.concealComment ? record.concealComment.content : ''}
        onChange={this.handleCommentChange.bind(this)}/>
      <Button type='primary'
              className='margin-t-2'
              onClick={this.handleConcealComment.bind(this, record)}>
        <FormattedMessage id='确定'/>
      </Button>
      <Button className='margin-t-2 margin-l-2' onClick={this.handleCancel.bind(this, record)}>
        <FormattedMessage id='取消'/>
      </Button>

    </div>
  }

  followUser (value) {
    this.props.getUserByNameOrEmail(value, this.props.programId, (data) => {
      this.setState({dataSource: data || []})
      const follower = data.followers.filter(item =>
        item.studentId === (data.searchUsers.length > 0 ? data.searchUsers[0].id : -1)
      )
      if (follower.length !== 0) {
        message.warning('请勿重复关注')
        return
      }
      this.follow(data.searchUsers[0].id)
    })
    this.search(value)
  }

  viewEvaluation (record) {
    const content = record.concealComment ? record.concealComment.content : ''
    const userName = this.getCompleteName(record.student)
    this.setState({content, userName, commentModalVisible: true})
  }

  getHasTags (currentStudentTags) {
    return currentStudentTags.map(userTag => userTag.tag.id)
  }

  handleSubmitEdit () {
    const {currentSelectedTagIds, currentSelectedStudentId} = this.state
    const {programId} = this.props
    this.props.editStudentTags(programId, currentSelectedStudentId, currentSelectedTagIds)
    this.setState({tagModalVisible: false})
  }

  render () {
    const {
      expandRowByClick, expandIconAsCell, expandedRowKeys, userName,
      commentModalVisible, content, tagModalVisible, currentSelectedTagIds
    } = this.state
    const {searchUsers, followers} = this.props.autoCompleteUsers
    const {students, myStudents, settings, userTags, programId, user} = this.props
    const options = searchUsers.map((user, idx) => {
      return <Option key={user.email} text={(user.name ? user.name : user.username)} value={user.email}>
        {user.name ? user.name : user.username}({user.email})
        {followers.find(follower => follower.studentId === user.id)
          ? <span style={{float: 'right', color: '#C0C0C0'}}><FormattedMessage id='已关注'/></span>
          : <span style={{float: 'right'}}><FormattedMessage id='未关注'/></span>
        }

      </Option>
    })

    const columns = [{
      title: <FormattedMessage id='姓名'/>,
      dataIndex: 'name',
      sorter: (a, b) => a.name.length - b.name.length,
      render: (text, record) => {
        return <Link to={this.gotoSection(record.student.id)}>{this.getCompleteName(record.student)}</Link>
      }
    },
      {
        title: <FormattedMessage id='任务卡总积分'/>,
        dataIndex: 'sumPoints',
        sorter: (a, b) => a.sumPoints - b.sumPoints
      },
      {
        title: 'Tag ',
        dataIndex: 'userTags',
        width: '30%',
        render: (userTags, record) => {
          return <div>
            {userTags.map(userTag => {
              const {tag} = userTag
              return <Tag key={tag.id} color={tag.color === 'default' ? '' : tag.color}>
                {tag.name}
              </Tag>
            })}
            <Tag
              style={{borderStyle: 'dashed'}}
              onClick={() => this.setState({
                tagModalVisible: true,
                currentSelectedTagIds: this.getHasTags(userTags),
                currentSelectedStudentId: record.student.id
              })}>
              <Icon type='plus'/> Add Tag
            </Tag>
          </div>
        }
      },
      {
        title: <FormattedMessage id='操作'/>,
        dataIndex: 'unFollow',
        render: (text, record, index) => {
          return <span>
          <a onClick={this.onExpandedRowsChange.bind(this, index, record)}><FormattedMessage id='评价'/></a>
          <Divider type="vertical"/>
          <a onClick={this.viewEvaluation.bind(this, record)}><FormattedMessage id='查看评价'/></a>
          <Divider type="vertical"/>
          <a onClick={this.unFollow.bind(this, record.student.id)}><FormattedMessage id='取消关注'/></a>
        </span>
        }

      }]

    return (
      <div className='follow-list'>
        <Card noHovering bordered={false} title={
          <SearchToolPane
            options={options}
            search={this.search.bind(this)}
            programId={programId}
            myStudents={myStudents}
            students={students}
            user={user}
            settings={settings}
            batchFollow={this.batchFollow.bind(this)}
            batchUnFollow={this.props.batchUnFollow}
            followUser={this.followUser.bind(this)}
          />
        }>

          <Table rowKey={(record, index) => index} pagination={false} columns={columns}
                 dataSource={myStudents}
                 expandRowByClick={expandRowByClick}
                 expandIconAsCell={expandIconAsCell}
                 expandedRowKeys={expandedRowKeys}
                 expandedRowRender={this.expandedRowRender.bind(this, settings)}
          />
        </Card>

        <CommentModal
          userName={userName}
          commentModalVisible={commentModalVisible}
          handleCancel={() => this.setState({commentModalVisible: false})}
          content={content}
        />

        <EditTagModal
          tagModalVisible={tagModalVisible}
          handleSubmitEdit={this.handleSubmitEdit.bind(this)}
          handleCancelEdit={() => this.setState({tagModalVisible: false})}
          currentSelectedTagIds={currentSelectedTagIds}
          handleSelectTagChange={(currentSelectedTagIds) => this.setState({currentSelectedTagIds})}
          userTags={userTags}
        />
      </div>
    )
  }
}

const mapStateToProps = state => ({
  autoCompleteUsers: state.autoCompleteUsers,
  settings: state.settings,
  userTags: state.userTags,
  students: state.students,
  user: state.user
})

const mapDispatchToProps = dispatch => ({
  getUserByNameOrEmail: (query, programId, callback) => dispatch(taskActions.getUserByNameOrEmail(query, programId, callback)),
  follow: (followerId, programId, callback) => dispatch(myStudentsActions.follow(followerId, programId, callback)),
  unFollow: (followerId, programId) => dispatch(myStudentsActions.unFollow(followerId, programId)),
  notification: (receiverId, programId, type) => dispatch(notification.notification(receiverId, programId, type)),
  addConcealComment: (studentId, programId, content) => dispatch(myStudentsActions.addConcealComment(studentId, programId, content)),
  getStudentTagsByProgramId: (programId) => dispatch(getStudentTagsByProgramId(programId)),
  editStudentTags: (programId, studentId, tagIds) => dispatch(editStudentTags(programId, studentId, tagIds)),
  getStudentsByPrograms: programId => dispatch(getStudentsByProgramId(programId)),
  batchFollow: (programId, tutorId, studentIds, callback) => dispatch(batchFollow(programId, tutorId, studentIds, callback)),
  batchUnFollow: (programId, tutorId, studentIds) => dispatch(batchUnFollow(programId, tutorId, studentIds)),

})

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(MyStudentBox))
